package io.renren.modules.medical.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.MedicalException;
import io.renren.common.result.ResultCodeEnum;
import io.renren.common.utils.ArabicToChineseConverterUtil;
import io.renren.modules.medical.dao.PatientDiseaseInformationDao;
import io.renren.modules.medical.entity.*;
import io.renren.modules.medical.entity.history.DrugHistoryEntity;
import io.renren.modules.medical.entity.history.NonDrugHistoryEntity;
import io.renren.modules.medical.entity.history.OperationHistoryEntity;
import io.renren.modules.medical.entity.history.PreviousDiseaseHistoryEntity;
import io.renren.modules.medical.service.*;
import io.renren.modules.medical.vo.medicalVo.DiseaseInfoDetailVo;
import io.renren.modules.medical.vo.medicalVo.info.DiseaseInfoSaveVo;
import io.renren.modules.medical.vo.medicalVo.info.DiseaseMapVo;
import io.renren.modules.medical.vo.medicalVo.info.TreatmentInfoSaveVo;
import io.renren.modules.medical.vo.weixinVo.ApiDiseaseListVo;
import io.renren.modules.medical.vo.weixinVo.ApiMedicationRecord;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@Service("patientDiseaseInformationService")
public class PatientDiseaseInformationServiceImpl extends ServiceImpl<PatientDiseaseInformationDao, PatientDiseaseInformationEntity> implements PatientDiseaseInformationService {
    private final DrugHistoryService drugHistoryService;

    private final NonDrugHistoryService nonDrugHistoryService;

    private final OperationHistoryService operationHistoryService;

    private final PreviousDiseaseHistoryService previousDiseaseHistoryService;

    private final PatientTreatmentInformationService patientTreatmentInformationService;

    private final IllSubService illSubService;

    private final PatientDoctorRelativeService patientDoctorRelativeService;


    @Override
    public Long saveDiseaseInfo(DiseaseInfoSaveVo diseaseInfoSaveVo) {
        diseaseInfoSaveVo.setId(null);
        // 先copy diseaseEntity
        PatientDiseaseInformationEntity patientDiseaseInformationEntity = new PatientDiseaseInformationEntity();
        BeanUtils.copyProperties(diseaseInfoSaveVo, patientDiseaseInformationEntity);

        // 将koaId保存到relative表中
        // 进行判断，如果当前要添加的信息的basicId和koaDiscrebId能查到值那就直接执行添加
        Long koaDescribeId = diseaseInfoSaveVo.getKoaDescribeId();
        Long patientBasicId = diseaseInfoSaveVo.getPatientBasicId();
        LambdaQueryWrapper<PatientDoctorRelativeEntity> relativeEntityWrapper = new LambdaQueryWrapper<>();
        relativeEntityWrapper.eq(PatientDoctorRelativeEntity::getPatientBasicId, patientBasicId);
        List<PatientDoctorRelativeEntity> relativeEntities = patientDoctorRelativeService.list(relativeEntityWrapper);
        PatientDoctorRelativeEntity one = relativeEntities.get(0);

        // 先找到relativeEntity表的和subId对应的parentId
        Long oneSubId = one.getSubId();
        IllSubEntity subEntity = illSubService.getById(oneSubId);

        if (relativeEntities.size() == 1 && subEntity.getParentId().equals(0L)) {
            // 当前是一级的subEntity，需要进行下一步操作：更新subEntity表
            IllSubEntity illSubEntity = illSubService.getById(koaDescribeId);
            LambdaQueryWrapper<PatientDoctorRelativeEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PatientDoctorRelativeEntity::getPatientBasicId, patientBasicId);
            PatientDoctorRelativeEntity relativeEntity = patientDoctorRelativeService.getOne(queryWrapper);
            relativeEntity.setSubId(illSubEntity.getId());
            relativeEntity.setSubTitle(illSubEntity.getTitle());
            patientDoctorRelativeService.updateById(relativeEntity);
        } else {
            // 如果不是一级的subEntity就说明当前要添加的信息不是第一次诊断
            List<Long> relativeIds = relativeEntities.stream().map(PatientDoctorRelativeEntity::getSubId).collect(Collectors.toList());
            if (!relativeIds.contains(koaDescribeId)) {
                // 判定1、如果subId和koaId不相等，说明是在添加新病症，需要创建新的relativeEntity
                PatientDoctorRelativeEntity patientDoctorRelativeEntity = new PatientDoctorRelativeEntity();
                IllSubEntity illSubEntity = illSubService.getById(koaDescribeId);
                patientDoctorRelativeEntity.setSubId(illSubEntity.getId());
                patientDoctorRelativeEntity.setSubTitle(illSubEntity.getTitle());
                // 从原来的relativeEntity表中获取到patientId
                patientDoctorRelativeEntity.setPatientId(one.getPatientId());
                patientDoctorRelativeEntity.setDoctorId(one.getDoctorId());
                patientDoctorRelativeEntity.setPatientBasicId(patientBasicId);
                patientDoctorRelativeService.save(patientDoctorRelativeEntity);
            }
            // 判定2、如果subId和koaId相等，说明是在同一病症下进行新的添加，不需要创建新的relativeEntity
        }

        // 从传来对象中抽取到几个历史值并保存
        saveHistory(diseaseInfoSaveVo, patientDiseaseInformationEntity);
        this.save(patientDiseaseInformationEntity);
        return patientDiseaseInformationEntity.getId();
    }

    private void saveHistory(DiseaseInfoSaveVo diseaseInfoSaveVo, PatientDiseaseInformationEntity patientDiseaseInformationEntity) {
        DiseaseMapVo treatmentMap = diseaseInfoSaveVo.getTreatmentMap();
        DrugHistoryEntity koaDrugHistory = treatmentMap.getKoaDrugHistory();
        NonDrugHistoryEntity koaNonDrugHistory = treatmentMap.getKoaNonDrugHistory();
        OperationHistoryEntity koaOperationHistory = treatmentMap.getKoaOperationHistory();
        PreviousDiseaseHistoryEntity previousHistory = treatmentMap.getPreviousHistory();
        if (koaDrugHistory != null && StringUtils.isNotEmpty(koaDrugHistory.getDrugName())) {
            koaDrugHistory.setIsKoa(1);
            drugHistoryService.save(koaDrugHistory);
            patientDiseaseInformationEntity.setKoaDrugHistoryId(koaDrugHistory.getId());
        }
        if (koaNonDrugHistory != null && StringUtils.isNotEmpty(koaNonDrugHistory.getTreatmentUsage())) {
            koaNonDrugHistory.setIsKoa(1);
            nonDrugHistoryService.save(koaNonDrugHistory);
            patientDiseaseInformationEntity.setKoaNonDrugHistoryId(koaNonDrugHistory.getId());
        }
        if (koaOperationHistory != null && StringUtils.isNotEmpty(koaOperationHistory.getOperationName())) {
            koaOperationHistory.setIsKoa(1);
            operationHistoryService.save(koaOperationHistory);
            patientDiseaseInformationEntity.setKoaOperationHistoryId(koaOperationHistory.getId());
        }
        if (previousHistory != null && StringUtils.isNotEmpty(previousHistory.getDiseaseName())) {
            previousDiseaseHistoryService.save(previousHistory);
            patientDiseaseInformationEntity.setPreviousHistoryId(previousHistory.getId());
        }
    }

    @Override
    public void updateDiseaseInfo(DiseaseInfoSaveVo diseaseInfoSaveVo) {
        // 先将四个历史表全部删除
        PatientDiseaseInformationEntity informationEntity = this.getById(diseaseInfoSaveVo.getId());
        Long koaDrugHistoryId = informationEntity.getKoaDrugHistoryId();
        Long koaNonDrugHistoryId = informationEntity.getKoaNonDrugHistoryId();
        Long koaOperationHistoryId = informationEntity.getKoaOperationHistoryId();
        Long previousHistoryId = informationEntity.getPreviousHistoryId();
        if (koaDrugHistoryId != null) {
            drugHistoryService.removeById(koaDrugHistoryId);
        }
        if (koaNonDrugHistoryId != null) {
            nonDrugHistoryService.removeById(koaNonDrugHistoryId);
        }
        if (koaOperationHistoryId != null) {
            operationHistoryService.removeById(koaOperationHistoryId);
        }
        if (previousHistoryId != null) {
            previousDiseaseHistoryService.removeById(previousHistoryId);
        }

        // 更新和保存
        PatientDiseaseInformationEntity patientDiseaseInformationEntity = new PatientDiseaseInformationEntity();
        BeanUtils.copyProperties(diseaseInfoSaveVo, patientDiseaseInformationEntity);

        // 从传来对象中抽取到几个历史值并保存
        saveHistory(diseaseInfoSaveVo, patientDiseaseInformationEntity);

        // 先从informationEntity中获取到koaId和subId 原来的
        Long basicId = informationEntity.getPatientBasicId();
        Long koaDescribeId = informationEntity.getKoaDescribeId();

        // 要更新koaDescribeId
        Long newKoaDescribeId = diseaseInfoSaveVo.getKoaDescribeId();
        //
        IllSubEntity newIllSubEntity = illSubService.getById(newKoaDescribeId);

        if (koaDescribeId.equals(newKoaDescribeId)) {
            // 如果新增的等于老的，那就直接更新
            this.updateById(patientDiseaseInformationEntity);
            return;
        }

        // 如果本来就有的话就不用修改直接删除原来的（新的关系表）
        LambdaQueryWrapper<PatientDoctorRelativeEntity> relativeEntityWrapper = new LambdaQueryWrapper<>();
        // 构造条件 subId等于要添加的disease的koaId并且basicId等于要添加的信息的basicId
        relativeEntityWrapper.eq(PatientDoctorRelativeEntity::getPatientBasicId, basicId);
        relativeEntityWrapper.eq(PatientDoctorRelativeEntity::getSubId, newKoaDescribeId);
        PatientDoctorRelativeEntity newRelativeEntity = patientDoctorRelativeService.getOne(relativeEntityWrapper);

        // 老的关系表
        LambdaQueryWrapper<PatientDoctorRelativeEntity> relativeEntityQueryWrapper = new LambdaQueryWrapper<>();
        relativeEntityQueryWrapper.eq(PatientDoctorRelativeEntity::getPatientBasicId, basicId);
        relativeEntityQueryWrapper.eq(PatientDoctorRelativeEntity::getSubId, koaDescribeId);
        PatientDoctorRelativeEntity oldRelativeEntity = patientDoctorRelativeService.getOne(relativeEntityQueryWrapper);

        // 获取到绑定basicId的disease表的数量
        LambdaQueryWrapper<PatientDiseaseInformationEntity> informationEntityWrapper = new LambdaQueryWrapper<>();
        // 构造条件，basicId和subId符合的（查看老关系的数量）
        informationEntityWrapper.eq(PatientDiseaseInformationEntity::getPatientBasicId, informationEntity.getPatientBasicId());
        informationEntityWrapper.eq(PatientDiseaseInformationEntity::getKoaDescribeId, koaDescribeId);
        int count = this.count(informationEntityWrapper);

        if (count > 1) {
            // 老关系数量大于1
            if (newRelativeEntity == null) {
                // 新的表没有的话就添加一个新的表
                PatientDoctorRelativeEntity patientDoctorRelativeEntity = new PatientDoctorRelativeEntity();
                patientDoctorRelativeEntity.setPatientId(oldRelativeEntity.getPatientId());
                patientDoctorRelativeEntity.setDoctorId(oldRelativeEntity.getDoctorId());
                patientDoctorRelativeEntity.setPatientBasicId(basicId);
                patientDoctorRelativeEntity.setSubId(newKoaDescribeId);
                patientDoctorRelativeEntity.setSubTitle(newIllSubEntity.getTitle());
                patientDoctorRelativeService.save(patientDoctorRelativeEntity);
            }
            // 如果有新的表就什么都不做，因为老表还有关联，所以不用删除
        } else if (count == 1) {
            // 老关系数量等于1
            if (newRelativeEntity != null) {
                // 新增的表如果有的话就直接删除老的
                patientDoctorRelativeService.removeById(oldRelativeEntity.getId());
            } else {
                // 如果新的表没有的话就直接把老的表改成新的表
                oldRelativeEntity.setSubId(newKoaDescribeId);
                oldRelativeEntity.setSubTitle(newIllSubEntity.getTitle());
                patientDoctorRelativeService.updateById(oldRelativeEntity);
            }
        } else {
            throw new MedicalException(ResultCodeEnum.INFORMATION_INSERT_ERROR.getCode(), "未找到要修改的基础表数据");
        }

        this.updateById(patientDiseaseInformationEntity);
    }

    @Override
    public DiseaseInfoDetailVo getDiseaseInfo(Long id) {
        // 先获取PatientDiseaseInformationEntity
        PatientDiseaseInformationEntity diseaseInformationEntity = this.getById(id);
        DiseaseInfoDetailVo diseaseInfoDetailVo = new DiseaseInfoDetailVo();
        BeanUtils.copyProperties(diseaseInformationEntity, diseaseInfoDetailVo);
        // 再根据四个个id封装值
        Long koaDrugHistoryId = diseaseInformationEntity.getKoaDrugHistoryId();
        Long koaNonDrugHistoryId = diseaseInformationEntity.getKoaNonDrugHistoryId();
        Long koaOperationHistoryId = diseaseInformationEntity.getKoaOperationHistoryId();
        Long previousHistoryId = diseaseInformationEntity.getPreviousHistoryId();
        diseaseInfoDetailVo.setTreatmentMap(new DiseaseMapVo());
        if (koaDrugHistoryId != null){
            DrugHistoryEntity drugHistoryEntity = drugHistoryService.getById(koaDrugHistoryId);
            if (drugHistoryEntity != null){
                diseaseInfoDetailVo.getTreatmentMap().setKoaDrugHistory(drugHistoryEntity);
            }
        }
        if (koaNonDrugHistoryId != null){
            NonDrugHistoryEntity nonDrugHistoryEntity = nonDrugHistoryService.getById(koaNonDrugHistoryId);
            if (nonDrugHistoryEntity != null){
                diseaseInfoDetailVo.getTreatmentMap().setKoaNonDrugHistory(nonDrugHistoryEntity);
            }
        }
        if (koaOperationHistoryId != null){
            OperationHistoryEntity operationHistoryEntity = operationHistoryService.getById(koaOperationHistoryId);
            if (operationHistoryEntity != null){
                diseaseInfoDetailVo.getTreatmentMap().setKoaOperationHistory(operationHistoryEntity);
            }
        }
        if (previousHistoryId != null){
            PreviousDiseaseHistoryEntity previousDiseaseHistoryEntity = previousDiseaseHistoryService.getById(previousHistoryId);
            if (previousDiseaseHistoryEntity != null){
                diseaseInfoDetailVo.getTreatmentMap().setPreviousHistory(previousDiseaseHistoryEntity);
            }
        }
        return diseaseInfoDetailVo;
    }

    /**
     * 根据subId获取到diseaseList
     */
    // TODO 动态获取patientInfoId
    @Override
    public List<ApiDiseaseListVo> diseaseList(Long subId) {
        Long patientInfoId = 6L;
        // 1、根据patientInfoId和subId找到对应的basicId
        LambdaQueryWrapper<PatientDoctorRelativeEntity> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(PatientDoctorRelativeEntity::getSubId, subId);
        wrapper1.eq(PatientDoctorRelativeEntity::getPatientId, patientInfoId);
        PatientDoctorRelativeEntity relativeEntity = patientDoctorRelativeService.getOne(wrapper1);
        if (relativeEntity == null){
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "没找到对应的病情关系");
        }

        // 2、找到所有的病情集合
        Long patientBasicId = relativeEntity.getPatientBasicId();
        LambdaQueryWrapper<PatientDiseaseInformationEntity> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(PatientDiseaseInformationEntity::getKoaDescribeId, subId);
        wrapper2.eq(PatientDiseaseInformationEntity::getPatientBasicId, patientBasicId);
        wrapper2.orderByAsc(BaseEntity::getCreateTime);
        List<PatientDiseaseInformationEntity> informationEntities = this.list(wrapper2);
        AtomicInteger count = new AtomicInteger(1);
        // 封装返回
        List<ApiDiseaseListVo> resultList = informationEntities.stream().map(item -> {
            ApiDiseaseListVo apiDiseaseListVo = new ApiDiseaseListVo();
            apiDiseaseListVo.setId(item.getId());
            Long koaDescribeId = item.getKoaDescribeId();
            IllSubEntity subEntity = illSubService.getById(koaDescribeId);
            apiDiseaseListVo.setKoaDescribe(subEntity.getLevelDescribe());
            apiDiseaseListVo.setTitle("第" + ArabicToChineseConverterUtil.convertToChinese(count.get()) + "次诊断");
            apiDiseaseListVo.setCreateTime(item.getCreateTime());
            count.getAndIncrement();
            return apiDiseaseListVo;
        }).collect(Collectors.toList());

        return resultList;
    }

    @Override
    public DiseaseInfoDetailVo getDiseaseDetailInfo(Long diseaseId) {
        // 先获取到基本信息
        DiseaseInfoDetailVo diseaseInfo = this.getDiseaseInfo(diseaseId);
        if (diseaseInfo == null){
            return null;
        }
        TreatmentInfoSaveVo treatmentInfo = patientTreatmentInformationService.getTreatmentInfo(diseaseId);
        diseaseInfo.setTreatmentInfo(treatmentInfo);
        IllSubEntity illSubEntity = illSubService.getById(diseaseInfo.getKoaDescribeId());
        diseaseInfo.setKoaDescribe(illSubEntity.getLevelDescribe());
        return diseaseInfo;
    }

    /**
     * 获取到所有的用药记录
     * @param subId
     * @return
     */
    @Override
    public ApiMedicationRecord getMedicationRecord(Long subId) {
        Long patientInfoId = 5L;
        ApiMedicationRecord medicationRecord = new ApiMedicationRecord();
        LambdaQueryWrapper<PatientDoctorRelativeEntity> relativeWrapper = new LambdaQueryWrapper<>();
        relativeWrapper.eq(PatientDoctorRelativeEntity::getPatientId, patientInfoId);
        relativeWrapper.eq(PatientDoctorRelativeEntity::getSubId, subId);
        List<PatientDoctorRelativeEntity> relativeList = patientDoctorRelativeService.list(relativeWrapper);
        if (relativeList == null || relativeList.size() <= 0){
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "空对象异常");
        }
        Long patientBasicId = relativeList.get(0).getPatientBasicId();

        // 根据basicId和subId找到所有的koaDrugIds
        LambdaQueryWrapper<PatientDiseaseInformationEntity> diseaseWrapper = new LambdaQueryWrapper<>();
        diseaseWrapper.eq(PatientDiseaseInformationEntity::getPatientBasicId, patientBasicId);
        diseaseWrapper.eq(PatientDiseaseInformationEntity::getKoaDescribeId, subId);
        List<PatientDiseaseInformationEntity> diseaseList = this.list(diseaseWrapper);
        if (diseaseList == null || diseaseList.size() <= 0){
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "空对象异常");
        }
        List<Long> koaDrugIds = diseaseList.stream().map(PatientDiseaseInformationEntity::getKoaDrugHistoryId).collect(Collectors.toList());

        // 封装koaDrug
        LambdaQueryWrapper<DrugHistoryEntity> koaDrugWrapper = new LambdaQueryWrapper<>();
        koaDrugWrapper.in(DrugHistoryEntity::getId, koaDrugIds);
        koaDrugWrapper.orderByDesc(DrugHistoryEntity::getStartTime);
        List<DrugHistoryEntity> koaDrugHistories = drugHistoryService.list(koaDrugWrapper);
        medicationRecord.setKoaDrugRecord(koaDrugHistories);

        // 根据diseaseList获取到所有的treatmentIds
        List<Long> diseaseIds = diseaseList.stream().map(BaseEntity::getId).collect(Collectors.toList());
        LambdaQueryWrapper<PatientTreatmentInformationEntity> treatmentWrapper = new LambdaQueryWrapper<>();
        treatmentWrapper.in(PatientTreatmentInformationEntity::getPatientDiseaseId, diseaseIds);
        treatmentWrapper.orderByDesc(BaseEntity::getCreateTime);
        List<PatientTreatmentInformationEntity> treatmentInfos = patientTreatmentInformationService.list(treatmentWrapper);
        if (treatmentInfos == null || treatmentInfos.size() <= 0){
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "空对象异常");
        }
        List<Long> drugIds = treatmentInfos.stream().map(PatientTreatmentInformationEntity::getDrugTreatmentId).collect(Collectors.toList());

        // 封装treatmentDrug
        List<DrugHistoryEntity> treatmentDrugHistories = drugHistoryService.listByIds(drugIds);
        medicationRecord.setDrugRecord(treatmentDrugHistories);

        return medicationRecord;
    }
}